<%-- 
    Document   : page
    Created on : 2014/8/21, 上午 09:27:06
    Author     : gjun
--%>

<%@page import="java.util.HashMap"%>
<%@page import="java.util.ArrayList"%>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@taglib  prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%
    String username = request.getParameter("username");
    String where =" ";
    if( username != null && !"".equals(username)){
        where =" where username like '%" + username+"%' ";
    }
    dao.BaseDAO y = new dao.BaseDAO();
    String sql="select count(*) as total from person " +where;
    String ary[]={};
    ArrayList list = y.query(sql, ary);
    String total  = (String)((HashMap)list.get(0)).get("total");
    int pagesize=2;//每頁的筆數
    int pages = Integer.parseInt(total) / pagesize; //總頁數
    if(Integer.parseInt(total) % pagesize !=0)
        pages++;
    String pageNo=request.getParameter("pageNo"); //使用者指定的頁碼
    if(pageNo==null)
        pageNo = "1";
    int index = (Integer.parseInt(pageNo) -1) * pagesize;//資料庫中開始的位置
    sql="select * from person "+where +" limit "+ index +", "+ pagesize;
    //ary=new String[]{index+"" , pagesize+""  };
    list = y.query(sql, ary);
    System.out.println(list);
    int lastPage = Integer.parseInt(pageNo) ==1 ? 1 : Integer.parseInt(pageNo)-1;
    int nextPage = Integer.parseInt(pageNo) ==pages ? pages : Integer.parseInt(pageNo)+1;
    request.setAttribute("list", list);
%>
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>JSP Page</title>
    </head>
    <body>
        <h1>Hello World!</h1>
        <form action="page.jsp" id="form1">
            查詢條件:<input type="text" name="username" value="${param.username}">
            <input type="hidden" name="pageNo" id="pageNo" value="1">
            <input type="submit">
        </form>
        <br>
        <input type="button" value="Last Page" onclick="goPage('<%= lastPage %>')">
        <!-- <a href="page.jsp?pageNo=<%= lastPage %>">上一頁</a> -->
        總共有<%= total %>筆, 目前頁碼:<%=pageNo %> , 每頁 <%= pagesize %> ,共有<%=pages %> 頁
        <!-- <a href="page.jsp?pageNo=<%= nextPage %>">下一頁</a> <br><br> -->
        <input type="button" value="Next Page" onclick="goPage('<%= nextPage %>')"><br><br>
        
        
        <input type="button" value="第3頁" onclick="goPage(3)"><br><br>
        
        <c:forEach var="x" items="${list}">
            ${x.id} , ${x.username} , ${x.tel} , ${x.birthday} <br>
        </c:forEach>
            
            <script>
                function goPage(x){
            
                    document.getElementById('pageNo').value= x ;
                    document.getElementById('form1').submit();
                }
             </script>
            
    </body>
</html>

